<template>
  <div class="auth">
    <el-form
      ref="inviteUserForm"
      :model="inviteUserForm"
      label-width="80px"
      label-position="top"
      :rules="rules"
      @submit.native.prevent
    >
      <el-form-item v-if="inviteHidd" label="用户" class="code" prop="userVal">
        <el-input v-model="inviteUserForm.userVal" placeholder="请输入受邀者手机或邮箱" size="small" @keyup.enter.native="findUser"></el-input>
      </el-form-item>
      <el-form-item v-if="inviteHidd" label="备注" class="code">
        <el-input v-model="inviteUserForm.remarks" placeholder="选填"  size="small"></el-input>
      </el-form-item>
      <div class="div_flex">
      <div class="div_flex_left" v-if="!inviteHidd">
          <div v-if="!inviteHidd" class="code_edit">
            <p class="title_first">ID</p>
            <p class="code_text"> {{ inviteUserForm.receiveUserId }}</p>
          </div>
          <div class="div_border"></div>
          <div v-if="!inviteHidd" class="code_edit">
            <p class="title">姓名</p>
            <p class="code_text" v-if="inviteUserForm.sendUserName"> {{ inviteUserForm.sendUserName}}</p>
            <p class="code_text" v-else>-</p>
          </div>
           <div class="div_border"></div>
          <div v-if="!inviteHidd" class="code_edit">
            <p class="title">手机</p>
            <p class="code_text" v-if="inviteUserForm.sendUserMobile"> {{ inviteUserForm.sendUserMobile }}</p>
            <p class="code_text" v-else> - </p>
          </div>
          <div class="div_border"></div>
          <div v-if="!inviteHidd" class="code_edit">
            <p class="title">备注</p>
            <p class="code_text" v-if="inviteUserForm.remarks"> {{ inviteUserForm.remarks }}</p>
            <p class="code_text" v-else> - </p>
        </div>
      </div>
      <!--    /* const roles = ['visitor', 'manager', 'finance', 'readOnly','campaignsReadOnly'] */
      /*
      // const roles=['系列管理员','账号财务','系列只读']
        游客：visitor:拥有所有权限及路由
        系列管理员：manager:除了(创建广告系列+财务)外的所有权限+路由
        账号财务：finance:除了公共页面之外 只能进入财务页面
        账号只读：readOnly:除了公共页面之外，只能进入数据概览页面&&只有查询及导出功能
		    系列只读：：campaignsReadOnly：同上
      */ -->
      <!-- <el-form-item label="用户访问权限和角色">
         <div class="">
           <el-radio v-model="inviteUserForm.receiveRole" label="finance">账号财务</el-radio>
          <p class="radio_height">管理充值、提现、结算选项</p>
        </div>
      </el-form-item> -->
      <div :class="inviteHidd ? '' : 'div_border_left'">
        <div :class="inviteHidd ? '' : 'div_line'"></div>
      <div :class="inviteHidd ? '' : 'div_flex_right'">
       <el-form-item label="用户访问权限和角色">
          <div class="div_flex_right_title_first">
          <el-radio v-model="inviteUserForm.receiveRole" label="advManager">广告管理员</el-radio>
          <p class="radio_height">管理团队中的所有广告系列报告和数据</p>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="div_flex_right_title_two">
          <el-radio v-model="inviteUserForm.receiveRole" label="readOnly">广告只读</el-radio>
          <p class="radio_height">查看团队中的所有广告系列报告和数据</p>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="div_flex_right_title">
          <el-radio v-model="inviteUserForm.receiveRole" label="manager">系列组管理员</el-radio>
          <p class="radio_height">查看报告、管理账号中的部分广告系列组</p>
        </div>
      </el-form-item>
      <el-form-item
        v-if="inviteUserForm.receiveRole==='manager'"
        label="广告系列组"
        class="ca-box"
        :prop="inviteUserForm.managerMap.length > 0? '' : 'managerMap'"
        :show-message="false"
      >
        <div class="all-box pointer">
          <em v-if="inviteUserForm.managerMap.length === 0" @click="handleAll(true,'managerMap')">全选</em>
          <em v-else @click="handleAll(false,'managerMap')">清空</em>
        </div>
        <el-cascader
          v-model="inviteUserForm.managerMap"
          :options="caOptions"
          size="small"
          style="width:480px;"
          :show-all-levels="false"
          :props="{ multiple: true }"
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <div class="div_flex_right_title">
          <el-radio v-model="inviteUserForm.receiveRole" label="campaignsReadOnly">系列组只读</el-radio>
          <p class="radio_height">查看团队中的部分广告系列组报告和数据</p>
        </div>
      </el-form-item>
      <el-form-item
        v-if="inviteUserForm.receiveRole==='campaignsReadOnly'"
        label="广告系列组"
        class="ca-box"
        :prop="inviteUserForm.readOnlyMap.length> 0 ?'' : 'readOnlyMap'"
        :show-message="false"
        :inline-message="true"
      >
        <div class="all-box pointer">
          <em v-if="inviteUserForm.readOnlyMap.length===0" @click="handleAll(true,'readOnlyMap')">全选</em>
          <em v-else @click="handleAll(false,'readOnlyMap')">清空</em>
        </div>
        <el-cascader
          v-model="inviteUserForm.readOnlyMap"
          :options="caOptions"
          size="small"
          style="width:480px;"
          :show-all-levels="false"
          :props="{ multiple: true }"
        ></el-cascader>
      </el-form-item>
      </div>
      </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  findOneUser,
  findRoleList
} from '@/api/user.js'
import {
  findcampaignGroudAll
} from '@/api/overView.js'

export default {
  name: 'Auth',
  props: {
    inviteHidd: Boolean,
    permissionInfo: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    var validateUserval = async(rule, value, callback) => {
      const res = await this.findUser()
      if (res.error) {
        callback(new Error(res.error))
      } else {
        this.inviteUserForm.receiveUserId = res.data.data.userId
        const userInfo = this.$store.state.user.userInfo
        this.inviteUserForm.sendUserName = userInfo.nickName || userInfo.mobile || userInfo.email
        callback()
      }
    }

    return {
      roleList: [],
      arrCamplist: '',
      list: [],
      inviteUserForm: {
        sendUserName: '', // 被邀请人的昵称
        sendUserMobile: '', //被邀请人的手机
        receiveUserId: '', // 被邀请人Id
        remarks: '', // 邀请备注
        userVal: undefined, // 用户手机号或者是邮箱
        receiveRole: 'readOnly', // 角色类型
        sendUserId: this.$store.state.user.userInfo.userId, // 发送邀请人id
        managerMap: [], // 系列管理员可以管理的广告系列
        readOnlyMap: [] // 系统制度可以查看的广告系列
      },
      rules: {
        userVal: [{
          required: true,
          message: '请输入受邀者手机或邮箱',
          trigger: 'change'
        },
        {
          validator: validateUserval,
          trigger: 'blur'
        }
        ],
        managerMap: [{
          required: true,
          trigger: 'change'
        }],
        readOnlyMap: [{
          required: true,
          trigger: 'change'
        }
        ]
      },
      caOptions: [],
      caLength: 0
    }
  },
  computed: {
    roleId() {
      if (!this.roleList.length) {
        return undefined
      } {
        const index = this.roleList.findIndex(item => {
          return item.name === this.inviteUserForm.receiveRole
        })
        if (index !== -1) {
          return this.roleList[index].id
        } else {
          return undefined
        }
      }
    },
    isType() {
      return this.$store.state.user.unit
    },
    unit() {
      return this.$store.state.user.unit
    }
  },

  watch: {
    inviteHidd: {
      deep: true,
      immediate: true,
      handler: function(val, oldVal) {
        this.inviteHidd = val
      }
    },
    permissionInfo: {
      handler: function(newval, oldval) {
        // 还原默认值
        if (Object.keys(newval).length) {
          const {
            userId,
            nickName,
            roleName,
            mobile,
            remarks
          } = newval
          if (newval.roleName === 'manager' || newval.roleName === 'campaignsReadOnly') {
            const arr = this.setCaInit(newval.map)
            if (newval.roleName === 'manager') {
              this.inviteUserForm.managerMap = arr
            } else {
              this.inviteUserForm.readOnlyMap = arr
            }
          }
          this.inviteUserForm.receiveUserId = userId
          this.inviteUserForm.sendUserName = nickName
          this.inviteUserForm.receiveRole = roleName
          this.inviteUserForm.sendUserMobile = mobile
          this.inviteUserForm.remarks = remarks
        }
      },
      // 深度观察监听
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.findRoleList()
    this.getSerialAll()
  },

  methods: {
    setCaInit(str) {
      let arr = []
      for (let i in str) {
        if (i === 'default') {
          let data = str[i]
          for (let j in data) {
            let dataKey = data[j]
            for (let v=0; v < dataKey.length; v++) {
                  let dataV= dataKey[v]
                  arr.push([ dataV])
                }
          }
        } else {
          let data = str[i]
          for (let j in data) {
              let dataKey = data[j]
              for (let k in dataKey) {
                let dataKeys= dataKey[k]
                dataKeys.org.forEach(item => {
                 arr.push([dataKeys.uuid, item.orgId ])
              })
              }
          }
        }
      }
    return arr
    },

    async findRoleList() {
      const res = await findRoleList()
      if (res.data.code === 20000) {
        this.roleList = res.data.data
      }
    },
    // 查询所有广告系列组
    async getSerialAll() {
      let data = {
        teamId: this.permissionInfo.teamId || window.localStorage.getItem('team-data')
      }
      const res = await findcampaignGroudAll(data)
      if (res.data.code === 20000) {
        let groudData = res.data.data
       console.log(groudData)
        let length = 0
        let arrData  = []
        // let arrData = [
        //   {
        //     value: 'default',
        //     label: '自助投放',
        //     children:[
        //       {
        //         value: this.unit,
        //         label: this.unit === 'RMB' ? '人民币' : '美元',
        //         children: []
        //       }
        //     ]
        //   },
        //   {
        //     value: 'secreKeys',
        //     label: '协同投放',
        //     children:[
        //       {
        //         value: this.unit,
        //         label: this.unit === 'RMB' ? '人民币' : '美元',
        //         children: []
        //       }
        //     ]
        //   }
        // ]
        for (let i in groudData) {
          console.log(i)
          // if (i === 'default') {
          //     let data = groudData[i]
          //       data.forEach(item => {
          //         arrData[0].children[0].children.push({
          //           value: item.id,
          //           label:item.name
          //         })
          //       })
          //       length += 1
          // } else
          if(i === 'secretKeys'){
              let data = groudData[i]
              console.log(groudData[i])
               for (let i in data) {
                 let dataXT = data[i]
                  let arr = []
                  if (dataXT.org.length > 0) {
                    let dataXTLen = dataXT.org
                    dataXTLen.forEach(item => {
                      if (dataXT.roleName === 'invalid_client') {
                        arr.push({
                          value: item.orgId,
                          label: item.orgName + '(已失效)',
                          disabled: true,
                        })
                      } else {
                        arr.push({
                          value: item.orgId,
                          label: item.orgName,
                        })
                      }
                    })
                  }
                  // arrData[1].children[0].children.push({
                  //   value: dataXT.uuid,
                  //   label: dataXT.secretName,
                  //   children: arr
                  // })
                   arrData.push({
                    value: dataXT.uuid,
                    label: dataXT.secretName,
                    children: arr
                  })
                  length += 1
                }
                length += 1
          }
        }
        // if (arrData[1].children[0].children.length === 0) {
        //     arrData[1] ={
        //     value: 'secreKeys',
        //     label: '协同投放',
        //     disabled: true
        //     }
        // }
         this.caOptions = arrData
        this.caLength = length
        return
      } else {
        this.caOptions = []
        this.caLength = 0
        return false
      }
    },
    // 搜索用户
    async findUser() {
      var phoneReg = /^1[3456789]\d{9}$/ // 手机号正则格式
      var emailReg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/ // 邮箱正则格式
      const phoneFlag = phoneReg.test(this.inviteUserForm.userVal)
      const emailFlag = emailReg.test(this.inviteUserForm.userVal)
      if (!phoneFlag && !emailFlag) {
        this.inviteUserForm.receiveUserId = undefined
        return {
          error: '请输入正确格式的手机号或者邮箱'
        }
      }
      const user = {}

      if (phoneFlag) {
        user.mobile = this.inviteUserForm.userVal
      } else {
        user.email = this.inviteUserForm.userVal
      }
      const res = await findOneUser(user)
      if (res.data.code === 20000) {
        this.inviteUserForm.receiveUserId = res.data.userId
        return res
      } else {
        this.inviteUserForm.receiveUserId = undefined
        if (res.data.code === 20012) {
          return {
            error: '不能邀请自己'
          }
        } else if (!res.data.data) {
          return {
            error: '该用户不存在'
          }
        } else {
          return {
            error: res.data.message
          }
        }
      }
    },
    // 全选
    handleAll(flag, key) {
      if (flag) {
        const arr = []
        this.caOptions.forEach(item => {
          if (item.value === 'default') {
            item.children.forEach(v => {
              v.children.forEach(index => {
                arr.push([item.value,v.value, index.value])
              })
            })
          } else {
            if (!item.disabled) {
               item.children.forEach(v => {
                  v.children.forEach(index => {
                    index.children.forEach(m => {
                   if (!m.disabled) {
                     arr.push([item.value,v.value, index.value, m.value])
                   }
                })
              })
            })
            }
          }
        })
        this.inviteUserForm[key] = JSON.parse(JSON.stringify(arr))
      } else {
        this.inviteUserForm[key] = []
      }
    },

    // 验证数据
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs['inviteUserForm'].validate((valid) => {
          if (valid) {
            if (this.inviteUserForm.receiveRole === 'manager' && this.inviteUserForm.managerMap.length <= 0) {
              this.$message.closeAll()
              this.$message.error('请选择广告系列组')
              return reject()
            }
            if (this.inviteUserForm.receiveRole === 'campaignsReadOnly' && this.inviteUserForm.readOnlyMap.length <=
                0) {
              this.$message.closeAll()
              this.$message.error('请选择广告系列组')
              return reject()
            }
            return resolve({ ...this.inviteUserForm,
              roleId: this.roleId
            })
          } else {
            return reject()
          }
        })
      })
    },
    clear() {
      this.$refs['inviteUserForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
 @import "~@/styles/variables.scss";
 div /deep/.el-radio__label {
  font-size: 14px;
  padding-left: 10px;
  color: #1D2129;
  font-family: PingFang SC;
  font-style: normal;
  font-weight: 400;
}
 .div_line {
      border-right: 1px solid #f7f7f9;
      height: 65px;
      width: 0%;
      position: absolute;
      bottom: 0;
      left: -1px;
      top: 100%;
    }
.div_flex{
  display: flex;
  .div_flex_left {
    // height: 355px;
    width: 220px;
    // border-right: 1px solid red;
    .code_edit {
    padding: 10px 0;
    width: 60px;
  .title_first {
    margin-top: -15px;
  }
 .title{
    margin-top: 25px;
  }
  .code_text {
      position: relative;
      top: 10px;
      color: #1D2129;
      font-size: 12px;
      font-size: 14px;
      font-weight: 500;
      font-family: PingFang SC;
      min-width: 172px;
      margin-bottom: 10px;
      text-overflow:ellipsis;
      white-space: nowrap;
      overflow:hidden;
    }
  }
}
  .div_border {
    width: 245px;
    height: 1px;
    border-bottom:1px solid #f7f7f9;
    position: absolute;
    margin-left: -24px;
    margin-top: 10px;
  }
  .div_border_left {
    border-left: 1px solid #f7f7f9;
    line-height: 12px;
    position:relative;
    top: -25px;
    height: 100%;
    //  border: 1px solid $borderColor2;
    //   position:relative;
    // top: 0px;
  }
  .div_flex_right {
    left: 30px;
    position:relative;
    top: 33px;
    .div_flex_right_title_first {
      position:relative;
      top: 5px;
    }
    .div_flex_right_title_two {
      position:relative;
      top: -5px;
    }
    .el-form-item .div_flex_right_title {
      font-size: 14px;
      font-family: PingFang SC;
      position: relative;
      top: -15px;
    }
  }
}
.code {
    .el-input {
      width:480px;
    }
    .el-button {
      margin-left: 10px;
    }
  }

  .chooseAll {
    position: absolute;
    right: 30%;
    top: -50px;
  }

  .user_role {
    margin-top: 10px;
  }

  .radio_height {
    color: rgba(51, 64, 74, 0.8);
    letter-spacing: 0.05em;
    font-size: 12px;
    line-height: 12px;
    height: 12px;
    margin-left: 25px;
  }

  .el-form-item.is-error {
    margin-bottom: 32px;
  }

  .ca-box.el-form-item.is-error {
    margin-bottom: 22px;
  }

  .ca-box {

    ::v-deep.el-form-item__label {
      font-size: 12px;
      left: 12px;
      font-family: "PingFangSC-Regular", PingFangSC, sans-serif !important;
    }

    .all-box {
      position: absolute;
      top: -18px;
      left: 360px;
      font-size: 12px;
      line-height: 12px;

      em {
        margin-left: 94px;
      }

    }

  }
</style>
